package cn.glc.daily.life.web.service.captcha.impl;

import cn.glc.daily.life.common.enums.CaptchaEnum;
import cn.glc.daily.life.common.exceptions.GlobalException;
import cn.glc.daily.life.infrastructure.po.TemplatePo;
import cn.glc.daily.life.model.dto.SendCodeDto;
import cn.glc.daily.life.web.service.captcha.abs.AbstractEmailCodeSend;
import cn.glc.daily.life.web.support.MailSupport;
import cn.simon.free.redis.component.RedisSupport;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.RandomStringGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.CaptchaBusinessExceptionEnum.CAPTCHA_SEND_FAIL_EXCEPTION;
import static cn.glc.daily.life.infrastructure.repository.mysql.MysqlRepositories.templateRepository;


/**
 * 邮箱发送注册验证码
 *
 * @author simon
 * @date 2020/6/1 16:27
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
@Component("EMAIL_SIGNUP")
public class EmailSignupCodeSend extends AbstractEmailCodeSend {
    /**
     * 邮箱验证码格式限制 数字加大写字母
     */
    private final char[][] pairs = {{'0', '9'}, {'A', 'Z'}};
    private final RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange(pairs).build();
    @Autowired
    private MailSupport mailSupport;

    @SneakyThrows
    @Override
    public boolean send(SendCodeDto sendCode) {
        TemplatePo templatePo = templateRepository.findByCode("SMS_SIGNUP");
        String captchaContent = templatePo.getContent();
        String key = CaptchaEnum.EMAIL_CAPTCHA.getPrefix().concat(sendCode.getNumber());
        if (RedisSupport.jedisStringSupport.exists(key)) {
            log.info("邮箱验证码,未过期,重新发送{}", mailSupport.send(sendCode.getNumber(), captchaContent.replaceAll("captcha", String.valueOf(RedisSupport.jedisStringSupport.get(key)))) ? "成功" : "失败");
            return true;
        }
        String captcha = generator.generate(6);
        if (RedisSupport.jedisStringSupport.setNxWithExpire(key, captcha, 5, TimeUnit.MINUTES)) {
            log.info("邮箱验证码发送{}", mailSupport.send(sendCode.getNumber(), captchaContent.replaceAll("captcha", captcha)));
            return true;
        }
        Optional.empty().orElseThrow(() -> new GlobalException(CAPTCHA_SEND_FAIL_EXCEPTION));
        return false;
    }
}
